(function(window) {
    function Snake(width, height, direction) {
        this.width = width || 20;
        this.height = height || 20;
        this.direction = direction || "right";
        this.body = [{
                x: 3,
                y: 2,
                color: "red"
            },
            {
                x: 2,
                y: 2,
                color: "orange"
            },
            {
                x: 1,
                y: 2,
                color: "orange"
            }
        ];
    }

    var eles = [];

    Snake.prototype.init = function(map) {
        remove();
        console.log(this.body.length);
        for (var i = 0; i < this.body.length; i++) {
            var dv = document.createElement("div");
            dv.style.position = "absolute";
            dv.style.width = this.width + "px";
            dv.style.height = this.height + "px";
            dv.style.backgroundColor = this.body[i].color;
            dv.style.left = this.body[i].x * this.width + "px";
            dv.style.top = this.body[i].y * this.height + "px";
            map.appendChild(dv);
            eles.push(dv);
        }
    }

    Snake.prototype.move = function(food, map) {
        for (var i = this.body.length - 1; i > 0; i--) {
            this.body[i].x = this.body[i - 1].x;
            this.body[i].y = this.body[i - 1].y;
        }
        switch (this.direction) {
            case "right":
                this.body[0].x+=1;
                break;
            case "left":
                this.body[0].x+=1;
                break;
            case "top":
                this.body[0].y+=1;
                break;
            case "bottom":
                this.body[0].y+=1;
                break;
        }
    }

    function remove() {
        // for (var i = 0; i < eles.length; i++) {
        // 	eles[i].parentElement.removeChild(eles[i]);
        // 	eles.splice(i, 1);
        // }
        // console.log(eles);
        
        var i = eles.length - 1;
        for (; i >= 0; i--) {
          //先从当前的子元素中找到该子元素的父级元素,然后再弄死这个子元素
          var ele = eles[i];
          //从map地图上删除这个子元素div
          ele.parentNode.removeChild(ele);
          eles.splice(i, 1);
        }
        console.log(eles);
    }
    window.Snake = Snake;
}(window));